package com.qianfeng.xinyihezi.xinyihezi.activity.activity_meng;

import android.app.ProgressDialog;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListView;

import com.qianfeng.xinyihezi.xinyihezi.R;
import com.qianfeng.xinyihezi.xinyihezi.adapter.adapter_meng.MyListViewAdapter;
import com.qianfeng.xinyihezi.xinyihezi.model.bean_meng.Goods;
import com.qianfeng.xinyihezi.xinyihezi.netinterface.RetrofitInterface;
import com.qianfeng.xinyihezi.xinyihezi.url.NetURL;

import java.util.List;

import retrofit2.Retrofit;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class StrategyActivity extends AppCompatActivity  implements AbsListView.OnScrollListener, AdapterView.OnItemClickListener, View.OnTouchListener, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private Retrofit mRetrofit;
    private RetrofitInterface mInterface;
    private ListView mListView;
    private List<Goods> mList;
    private MyListViewAdapter mAdapter;
    private int page = 1;
    private boolean isLoaded;
    private ImageView mImageView;
    private float mFirstY;
    private float mCurrentY;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private ProgressDialog mDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_strategy);
        initView();
        initData();
        setData();
        setListener();
    }
    private void initView() {
        mImageView = (ImageView) findViewById(R.id.iv_item_listview_returntop);
        mListView = (ListView) findViewById(R.id.lv_strategy);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srlayout);
        mDialog = new ProgressDialog(this);
        mDialog.setMessage("加载中...");
    }
    private void initData() {
        mList = new ArrayList<>();
        mRetrofit = new Retrofit.Builder()
                // 设置基地址
                .baseUrl(NetURL.HEAD_URL)
                // 设置转换工厂  用于Json解析
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // 初始化接口实例
        mInterface = mRetrofit.create(RetrofitInterface.class);
        loadData();
    }
    private void loadData() {
        mDialog.show();
        mInterface.getNetData(page).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    String result = "";
                    try {
                        result = response.body().string().toString();
                        JSONObject object = new JSONObject(result);
                        JSONObject data = object.optJSONObject("data");
                        JSONArray strategy = data.optJSONArray("strategy");
                        for (int i = 0; i < strategy.length(); i++) {
                            JSONObject jsonObject = strategy.optJSONObject(i);
                            Goods goods = new Goods();
                            goods.collection_num = jsonObject.optString("collection_num");
                            goods.description = jsonObject.optString("description");
                            goods.image = jsonObject.optString("image");
                            goods.logo_image = jsonObject.optString("logo_image");
                            goods.market_time = jsonObject.optString("market_time");
                            goods.page_views = jsonObject.optString("page_views");
                            goods.refer_content = jsonObject.optString("refer_content");
                            goods.refer_type = jsonObject.optString("refer_type");
                            goods.share_content = jsonObject.optString("share_content");
                            goods.share_image = jsonObject.optString("share_image");
                            goods.share_title = jsonObject.optString("share_title");
                            goods.share_url = jsonObject.optString("share_url");
                            goods.stra_id = jsonObject.optString("stra_id");
                            goods.title = jsonObject.optString("title");
                            mList.add(goods);
                        }
                        mAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        mDialog.dismiss();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("123", "这是为什么");
            }
        });
    }
    private void setData() {
        mAdapter = new MyListViewAdapter(mList, this);
        mListView.setAdapter(mAdapter);
    }

    private void setListener() {
        mListView.setOnScrollListener(this);
        mListView.setOnItemClickListener(this);
        mListView.setOnTouchListener(this);
        mImageView.setOnClickListener(this);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }
    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {
        if (isLoaded && i == SCROLL_STATE_IDLE) {
            page++;
            loadData();
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {
        isLoaded = i + i1 == i2;
        if (i == 0 && mImageView.getVisibility() == View.VISIBLE) {
            mImageView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(this, DetailsActivity.class);
        intent.putExtra("title",mList.get(i).title);
        intent.putExtra("icon",mList.get(i).image);
        intent.putExtra("time",mList.get(i).market_time);
        intent.putExtra("stra_id",mList.get(i).stra_id);
        startActivity(intent);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mFirstY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                mCurrentY = event.getY();
                if (mCurrentY - mFirstY > 0 && mImageView.getVisibility() == View.GONE) {
                    mImageView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.push_bottom_in));
                    mImageView.setVisibility(View.VISIBLE);
                } else if (mFirstY - mCurrentY > 0 && mImageView.getVisibility() == View.VISIBLE) {
                    mImageView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.push_bottom_out));
                    mImageView.setVisibility(View.GONE);
                }
                break;
            case MotionEvent.ACTION_UP:

                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_item_listview_returntop:
                mListView.setSelection(0);
                mImageView.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        mSwipeRefreshLayout.setRefreshing(false);
        mList.clear();
        mAdapter.notifyDataSetChanged();
        loadData();
    }
}
